﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using Wedn.Core.Common;
using Wedn.Core.Entity;
using Wedn.Core.Service;
using Wedn.Core.Utility;

namespace Wedn.Web.UI.Admin.Handler
{
    /// <summary>
    /// PostAjax文章异步处理类
    /// </summary>
    public class PostAjax : IHttpHandler
    {
        HttpContext currentContext;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            this.currentContext = context;
            switch (RequestHelper.QueryString("action", true))
            {
                case "loadpostlist":
                    LoadPostList();
                    break;
                case "loadcategorylist":
                    LoadCategoryList();
                    break;
                case "loadtaglist":
                    LoadTagList();
                    break;
                case "publish":
                    PublishPost();
                    break;
                default:
                    break;
            }
        }

        #region 加载文章列表
        private void LoadPostList()
        {
            int pageIndex = RequestHelper.QueryInt("page", 1);
            int pageSize = RequestHelper.QueryInt("rows", 10);
            PostManager postManager = new PostManager();
            int total = 0;
            List<Post> dblist = postManager.GetPostList(null, PostStatus.Default, PostType.Post, -1, -1, null, null, pageSize, pageIndex, "post_pubdate", 0, out total);
            List<PostView> viewList = new List<PostView>();
            foreach (var item in dblist)
            {
                if ((PostStatus)item.Status != PostStatus.AutoDraft)
                {
                    PostView postView = new PostView();
                    postView.Id = item.Id;
                    postView.Title = item.Title;
                    postView.Author = item.Author.NickName;
                    postView.Category = item.CategoryLink;
                    postView.Tag = item.TagLink;
                    postView.CommentCount = item.CommentCount;
                    postView.PubDate = StringHelper.DateTimeToChsStr(item.PubDate);
                    if (item.Status != (int)PostStatus.Draft)
                    {
                        if (item.PubDate < DateTime.Now)
                            postView.Status = "已发布";
                        else if (item.PubDate >= DateTime.Now)
                            postView.Status = "待发布";
                    }
                    else
                    {
                        postView.Status = "草稿";
                    }
                    viewList.Add(postView);
                }
            }
            var data = new { total = total, rows = viewList };
            JavaScriptSerializer jsSer = new JavaScriptSerializer();
            currentContext.Response.Write(jsSer.Serialize(data));
        }
        #endregion

        #region 加载标签
        private void LoadTagList()
        {
            TermManager termManager = new TermManager();
            List<Term> tempList = termManager.GetTermList();
            JavaScriptSerializer jsSer = new JavaScriptSerializer();
            currentContext.Response.Write(jsSer.Serialize(tempList));
            currentContext.Response.End();
            //foreach (var item in tempList)
            //{
            //    if (item.Count>0)
            //    {

            //    }
            //}
        }
        #endregion

        #region 加载类别列表
        List<Term> categoryList = null;
        int level = 0;
        /// <summary>
        /// 加载类别列表
        /// </summary>
        private void LoadCategoryList()
        {
            TermManager termManager = new TermManager();
            categoryList = termManager.GetTermList(Core.Common.TermType.PostCategory);
            //System.Web.Script.Serialization.JavaScriptSerializer javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            //string jsonStr = javaScriptSerializer.Serialize(categoryList);
            StringBuilder sbd = new StringBuilder();
            string format = "<li class=\"level-{0}\">\r\n<label><input type=\"checkbox\" class=\"post-category\" value=\"{1}\" />{2}</label>\r\n";
            foreach (var item in categoryList)
            {
                //int level = 0;
                //int pid = item.ParentId;
                //while (pid != 0)
                //{
                //    level++;
                //    pid = categoryList.Find((cat) => { return cat.Id == pid; }).ParentId;
                //}
                if (item.ParentId == 0)
                {
                    sbd.AppendFormat(format, level, item.Id, item.Name);
                    LoadCategory(sbd, item.Id);
                    sbd.Append("</li>\r\n");
                }
            }
            currentContext.Response.Write(sbd.ToString());
            currentContext.Response.End();
        }
        /// <summary>
        /// 递归加载类别列表
        /// </summary>
        private void LoadCategory(StringBuilder sbd, int id)
        {
            level++;
            List<Term> tempList = categoryList.FindAll((term) => { return term.ParentId == id; });
            if (tempList.Count == 0)
            {
                level--;
                return;
            }
            string format = "<li class=\"level-{0}\">\r\n<label><input type=\"checkbox\" class=\"post-category\" value=\"{1}\" />{2}</label>\r\n";
            sbd.Append("<ul class=\"children\">\r\n");
            foreach (var item in tempList)
            {
                sbd.AppendFormat(format, level, item.Id, item.Name);
                LoadCategory(sbd, item.Id);
                sbd.Append("</li>\r\n");
            }
            sbd.Append("</ul>\r\n");
            level--;
        }
        #endregion

        #region 文章发布
        /// <summary>
        /// 文章发布
        /// </summary>
        private void PublishPost()
        {
            //1.存储标签, 提取出Term 的ID 数组
            TermManager termManager = new TermManager();
            string[] postTags = RequestHelper.FormString("post_tag").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            List<Term> termList = new List<Term>();
            foreach (var tag in postTags)
            {
                termList.Add(new Term() { Name = tag, Slug = StringHelper.UrlEncode(tag), ParentId = 0, Type = 0 });
            }
            int[] postTagsId = termManager.Insert(termList);
            string[] postCategorysId = RequestHelper.FormString("post_category").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            List<int> termsId = new List<int>(postTagsId);
            foreach (var id in postCategorysId)
            {
                termsId.Add(Convert.ToInt32(id));
            }
            //2.存储文章post_category
            PostManager postManager = new PostManager();
            Post post = new Post();
            //取表单中日期时间字符串
            string tempDate = RequestHelper.FormString("post_pubdate");
            //如果为空则默认为当前时间
            DateTime pubdate = string.IsNullOrEmpty(tempDate) ? DateTime.Now : Convert.ToDateTime(tempDate);
            post.Slug = StringHelper.UrlEncode(RequestHelper.FormString("post_slug"));
            post.Title = RequestHelper.FormString("post_title");
            post.PubDate = pubdate;
            post.Update = pubdate;
            post.Content = RequestHelper.FormString("post_content");
            post.Excerpt = RequestHelper.FormString("post_excerpt");
            post.Template = RequestHelper.FormString("post_template");
            post.AutherId = RequestHelper.FormInt("post_auther_id", 1);
            post.CommentStatus = RequestHelper.FormInt("post_comment_status", 0);
            post.Status = RequestHelper.FormInt("post_status", 0);
            post.Type = RequestHelper.FormInt("post_type", 0);
            post.IsTop = RequestHelper.FormString("post_istop") == "true";
            post.PingStatus = RequestHelper.FormInt("post_ping_status", 0);
            post.Password = RequestHelper.FormString("post_password");
            int postId = -1;
            try
            {
                postId = postManager.Insert(post);
            }
            catch (Exception ex) { currentContext.Response.Write(ex.Message); currentContext.Response.End(); }
            if (postId == -1)
            {
                currentContext.Response.Write("发布失败, 请重试!");
                currentContext.Response.End();
            }
            //3. 保存关系
            RelationManager relManager = new RelationManager();
            //int res = relManager.Insert(postId, ObjectType.Post, postTagsId);
            int res = relManager.Insert(postId, ObjectType.Post, termsId.ToArray());
            currentContext.Response.Write("success&" + post.Url);
        }
        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}